#include "bookdatacollector.h"

#include <QDialogButtonBox>
#include <QGridLayout>
#include <QLineEdit>
#include <QLabel>
#include <QRegExp>
#include <QRegExpValidator>

BookDataCollector::BookDataCollector( QWidget *parent )
    : QDialog( parent )
{
	m_pButtonBox = new QDialogButtonBox( QDialogButtonBox::Ok |
	                                     QDialogButtonBox::Cancel );

	m_pBookIdLabel = new QLabel( "ID" );
	m_pBookTitleLabel = new QLabel( "Title" );
	m_pBookAuthorLabel = new QLabel( "Author" );
	m_pBookYearLabel = new QLabel( "Year" );
	m_pBookDescriptionLabel = new QLabel( "Description" );
	m_pBookPriceLabel = new QLabel( "Price" );

	m_pBookIdText = new QLineEdit;
	QRegExp idRegExp( "^([0-9]+)$" );
	m_pBookIdText->setValidator( new QRegExpValidator( idRegExp, this ) );

	m_pBookTitleText = new QLineEdit;
	QRegExp titleRegExp( "^([a-zA-Z ]+)$" );
	m_pBookTitleText->setValidator( new QRegExpValidator( titleRegExp, this ) );

	m_pBookAuthorText = new QLineEdit;
	QRegExp authorRegExp( "^([a-zA-Z ]+)$" );
	m_pBookAuthorText->setValidator( new QRegExpValidator( authorRegExp, this ) );

	m_pBookYearText = new QLineEdit;
	QRegExp yearRegExp( "^([0-9]+)$" );
	m_pBookYearText->setValidator( new QRegExpValidator( yearRegExp, this ) );

	m_pBookDescriptionText = new QLineEdit;
	QRegExp descriptionRegExp( "^([a-zA-Z ]+)$" );
	m_pBookDescriptionText->setValidator( new QRegExpValidator( descriptionRegExp, this ) );

	m_pBookPriceText = new QLineEdit;
	QRegExp priceRegExp( "^([0-9]+)$" );
	m_pBookPriceText->setValidator( new QRegExpValidator( priceRegExp, this ) );

	m_pLayout = new QGridLayout;
	m_pLayout->addWidget( m_pBookIdLabel, 0, 0 );
	m_pLayout->addWidget( m_pBookTitleLabel, 1, 0 );
	m_pLayout->addWidget( m_pBookAuthorLabel, 2, 0 );
	m_pLayout->addWidget( m_pBookYearLabel, 3, 0 );
	m_pLayout->addWidget( m_pBookDescriptionLabel, 4, 0 );
	m_pLayout->addWidget( m_pBookPriceLabel, 5, 0 );
	m_pLayout->addWidget( m_pBookIdText, 0, 1 );
	m_pLayout->addWidget( m_pBookTitleText, 1, 1 );
	m_pLayout->addWidget( m_pBookAuthorText, 2, 1 );
	m_pLayout->addWidget( m_pBookYearText, 3, 1 );
	m_pLayout->addWidget( m_pBookDescriptionText, 4, 1 );
	m_pLayout->addWidget( m_pBookPriceText, 5, 1 );
	m_pLayout->addWidget( m_pButtonBox, 6, 0, 1, 2 );

	connect( m_pButtonBox, SIGNAL( accepted() ), this, SLOT( accept() ) );
	connect( m_pButtonBox, SIGNAL( rejected() ), this, SLOT( reject() ) );

	setLayout( m_pLayout );
}

Book BookDataCollector::getBook()
{
	return m_book;
}

void BookDataCollector::accept()
{
	m_book.setId( m_pBookIdText->text().toInt() );
	m_book.setTitle( m_pBookTitleText->text() );
	m_book.setAuthor( m_pBookAuthorText->text() );
	m_book.setYear( m_pBookYearText->text().toInt() );
	m_book.setDescription( m_pBookDescriptionText->text() );
	m_book.setPrice( m_pBookPriceText->text().toInt() );

	done( Accepted );
}

void BookDataCollector::reject()
{
	m_book = Book();

	done( Rejected );
}
